package executor

import (
	"xin-job/core/biz"
)

var i = &ExecutorBizImpl{}

func GetExecutorBizImpl() *ExecutorBizImpl {
	return i
}

type ExecutorBizImpl struct {
}

// 心跳判断执行器是否启动
func (c *ExecutorBizImpl) Beat() biz.Return[string] {
	return biz.Return[string]{
		Code: 200,
		Msg:  "success",
	}
}

// 判断任务是否在执行。
func (c *ExecutorBizImpl) IdleBeat(idleBeatParam *biz.IdleBeatParam) biz.Return[string] {
	r := biz.Return[string]{
		Code: 200,
		Msg:  "success",
	}
	isRun := GetInstance().IsRun(idleBeatParam.JobId)
	if isRun {
		r.Code = 500
		r.Msg = "job is run"
	}
	return r
}

// 执行任务
func (c *ExecutorBizImpl) Run(triggerParam *biz.TriggerParam) biz.Return[string] {
	result := biz.Return[string]{
		Code:    200,
		Msg:     "success",
		Content: "success",
	}

	// 加载任务
	h := GetInstance().LoadHandler(triggerParam.ExecutorHandler)
	if h == nil {
		result.Code = 500
		result.Msg = "No handlers found"
		result.Content = "No handlers found"
	} else {
		// 执行任务
		GetInstance().RunHandler(h, *triggerParam)
	}

	return result
}

// 杀死任务
func (c *ExecutorBizImpl) Kill(killParam *biz.KillParam) biz.Return[string] {
	r := biz.Return[string]{
		Code: 200,
		Msg:  "success",
	}
	err := GetInstance().Kill(killParam.JobId)
	if err != nil {
		r.Code = 500
		r.Msg = err.Error()
	}

	return r
}

// 查看执行器日志
func (c *ExecutorBizImpl) Log(logParam *biz.LogParam) biz.Return[biz.LogResult] {
	// TOOD 日志
	return biz.Return[biz.LogResult]{}
}
